package src.demo;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.gson.*;
import okhttp3.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @author 23050
 * @version 1.0
 * @description: TODO
 * @date 2025/2/28 23:23
 */
public class AliCompletion {

    public static void main(String[] args) throws IOException {
        try {
            String prompt = "public static void main";
            long start = System.currentTimeMillis();
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
//            RequestBody body = RequestBody.create(mediaType, "{\n  \"model\": \"qwen-coder-turbo\",\n  \"prompt\": \"public static void main, \" \n}");
            RequestBody body = RequestBody.create(mediaType, "{\n" +
                    "  \"model\": \"qwen-coder-turbo\",\n" +
                    "  \"prompt\": \"" +
                    prompt +
                    " \",\n" +
                    "  \"max_tokens\": 32\n" +
                    "}");
//
            Request request = new Request.Builder()
                    .url("https://dashscope.aliyuncs.com/compatible-mode/v1/completions")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .addHeader("Authorization", "Bearer sk-5bffade0f3fb46d49abf169956ca460e")
                    .build();
            Response response = client.newCall(request).execute();

            String jsonStr = response.body().string();
            // 解析 JSON 字符串
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            // 获取 choices 数组
            JSONArray choicesArray = jsonObject.getJSONArray("choices");
            if (choicesArray != null && !choicesArray.isEmpty()) {
                // 获取数组的第一个元素
                JSONObject firstChoice = choicesArray.getJSONObject(0);
                // 提取 text 属性
                String text = firstChoice.getString("text");
                System.out.println(text);
            }

            long end = System.currentTimeMillis();
            System.out.println(end-start);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
